<?php

namespace App\Jobs;

use App\Models\CurveOrderRecord;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Artisan;

class CurveOrderPlan implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $curve_order = null;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($curve_order)
    {
        $this->curve_order = $curve_order;
    }

    /**
     * 规划曲线订单增长模型
     *
     * @return void
     */
    public function handle()
    {
        $expect_total_read_num = $this->curve_order->expect_read_num - $this->curve_order->initialization_read_num;

        $minutes = $this->curve_order->expect_time * 12;//分钟区间


        $temp = [];

        for ($i = 1; $i < $minutes; $i++) {

            $temp[] = sqrt(pow($i, 3));

        }

        $temp = array_reverse($temp);

        $total_index = array_sum($temp);

        $time = Carbon::now();

        foreach ($temp as  $item) {

            $read_num_incr = ($item / $total_index) * $expect_total_read_num;

            if($read_num_incr >= 1){
                //插入数据库
                CurveOrderRecord::query()->updateOrCreate([
                    'expect_time' => $time->toDateTime(),
                    'order_id' => $this->curve_order->id
                ], [
                    'expect_read_num' => $read_num_incr
                ]);
            }


            $time->addMinutes(5);//五分钟一次


        }
        Artisan::call('curve_order:insert');

    }
}
